<template>
    <div class="project-management-container">
      <div class="header">
        <div class="form-item">
          <el-button size="small" type="primary" @click="openDialog">创建项目</el-button>
        </div>
        <div class="form-item">
          <el-button size="small" type="primary" @click="handleSearch">搜索</el-button>
        </div>
        <div class="form-item">
          <span>状态：</span>
          <el-select size="small" v-model="status" placeholder="请选择">
            <el-option :key="-1" label="所有" value=""></el-option>
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div class="form-item">
          <span>项目名：</span>
          <el-input size="small" v-model="projectName" placeholder="请输入内容"></el-input>
        </div>
      </div>
  
      <el-empty v-if="!projectDatas.length" description="数据为空"></el-empty>
      <div v-else class="project-cards">
        <el-card class="project-card" v-for="(project, index) in projectDatas" :key="index">
          <div class="project-info">
            <p><strong>项目名称：</strong>{{ project.projectName }}</p>
            <p><strong>评估方法：</strong>{{ project.evaluationMethod }}</p>
            <p><strong>计算模型：</strong>{{ project.calculationModel }}</p>
            <p><strong>项目状态：</strong>{{ project.status }}</p>
          </div>
          <el-button 
            v-if="project.status === '未提交'" 
            type="primary" 
            size="small"
            @click="beginEvaluation(index)"
          >
            评估
          </el-button>
          <span v-if="project.status === '评估中...'">评估中...</span>
          <el-button 
            v-if="project.status === '下一步'" 
            type="success" 
            size="small"
            @click="goToNextStep"
          >
            下一步
          </el-button>
          <el-button type="text" size="small" @click="toDetail">详情</el-button>
        </el-card>
  
        <div class="block-pagination">
          <el-pagination 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange" 
            :current-page="pageNum"
            :page-sizes="[100, 200, 300, 400]" 
            :page-size="100" 
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
  
      <el-dialog :visible.sync="dialogVisible" title="创建新项目" width="50%">
        <el-form :model="form" label-width="120px" :rules="rules" ref="form" status-icon>
          <el-form-item label="项目名称" prop="projectName" required>
            <el-input v-model="form.projectName" placeholder="请输入项目名称"></el-input>
          </el-form-item>
          
          <el-form-item label="评估方法" prop="evaluationMethod" required>
            <el-select v-model="form.evaluationMethod" placeholder="请选择评估方法">
              <el-option label="估算功能点法" value="method1"></el-option>
              <el-option label="方法二" value="method2"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="计算模型" prop="calculationModel" required>
            <el-select v-model="form.calculationModel" placeholder="请选择计算模型">
              <el-option label="智谱清言（推荐）" value="model1"></el-option>
              <el-option label="Chatgpt" value="model2"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="上传文件" prop="fileList">
            <el-upload
              :action="'http://localhost:8080/project'"
              :before-upload="beforeUpload"
              :on-change="handleFileChange"
              :file-list="fileList"
              accept=".doc,.docx"
              :limit="1"
              :headers="uploadHeaders"
              :data="{ userId: userId }"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm">确定</el-button>
            <el-button @click="closeDialog">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import { getProjects } from '@/api/project';
  import router from '@/router';
  
  export default {
    name: 'ProjectManagement',
    data() {
      return {
        dialogVisible: false,
        form: {
          projectName: '',
          evaluationMethod: '',
          calculationModel: '',
        },
        fileList: [],
        projectDatas: [],
        pageNum: 1,
        pageSize: 10,
        status: "",
        projectName: '',
        total: 0,
        type: this.$store.getters.type,
        userId: this.$store.getters.id,
        options: [
          { label: "未评估", value: "UN_EVALUATE" },
          { label: "已评估", value: "EVALUATE" }
        ],
        rules: {
          projectName: [
            { required: true, message: '请输入项目名称', trigger: 'blur' }
          ],
          evaluationMethod: [
            { required: true, message: '请选择评估方法', trigger: 'change' }
          ],
          calculationModel: [
            { required: true, message: '请选择计算模型', trigger: 'change' }
          ],
        },
        uploadHeaders: {
          'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes',
          'userId': this.userId
        }
      };
    },
    mounted() {
      this.init();
    },
    methods: {
      getList() {
        const { pageNum, pageSize, status, projectName, type, userId, id } = this;
        getProjects({
          pageNum,
          pageSize,
          status,
          projectName,
          type,
          userId,
          id,
        }).then(res => {
          this.projectDatas = res.data.items;
          this.total = res.data.total;
          console.log('Projects loaded:', this.projectDatas);
        }).catch(error => {
          console.error('Error fetching project data:', error);
          this.$message.error('获取项目列表失败');
        });
      },
      init() {
        this.pageNum = 1;
        this.pageSize = 10;
        this.getList();
      },
      handleSearch() {
        this.init();
      },
      toDetail() {
        router.push('/detail');
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.pageNum = val;
        this.getList();
      },
      openDialog() {
        this.dialogVisible = true;
      },
      closeDialog() {
        this.dialogVisible = false;
      },
      beforeUpload(file) {
        const isWord = file.type === 'application/msword' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        if (!isWord) {
          this.$message.error('上传文件只能是 Word 格式!');
        }
        return isWord;
      },
      handleFileChange(file, fileList) {
        this.fileList = fileList.slice(-1);
      },
      submitForm() {
        this.$refs.form.validate((valid) => {
          if (valid && this.fileList.length > 0) {
            const formData = new FormData();
            formData.append('file', this.fileList[0].raw);
            formData.append('projectName', this.form.projectName);
            formData.append('userId', this.userId);
  
            axios.post('http://localhost:8080/project', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes'
              }
            })
            .then(response => {
              console.log('Response data:', response.data);
              if (response.data.id) {
                console.log('服务器返回项目ID')}
                else{
                  console.log('服务器未返回项目ID')
                };
              this.$message.success('项目已创建并提交到服务器');
              const newProject = {
                projectName: this.form.projectName,
                evaluationMethod: this.form.evaluationMethod,
                calculationModel: this.form.calculationModel,
                status: '未提交',
                id: response.data.id // 自定义id
              };
              
              this.projectDatas.push(newProject);
              this.getList();
              this.closeDialog();
              this.resetForm();
            })
            .catch(error => {
              this.$message.error('提交项目失败');
              console.error('Error:', error);
            });
          } else {
            this.$message.error('请完整填写所有信息并上传文件');
          }
        });
      },
      resetForm() {
        this.form = {
          projectName: '',
          evaluationMethod: '',
          calculationModel: '',
        };
        this.fileList = [];
      },
      beginEvaluation(index) {
        console.log('Attempting to begin evaluation for index:', index);
        const project = this.projectDatas[index];
        console.log('Project at index:', project);
  
        if (!project) {
          this.$message.error('项目不存在');
          return;
        }
  
        if (!project.id) {
          this.$message.error('项目ID无效');
          return;
        }
  
        axios.post(`http://localhost:8080/project/begin/${project.id}`, null, {
          headers: {
            'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes'
          }
        })
        .then(response => {
          if (response.data.code === 1) {
            project.status = '评估中...';
            this.pollProjectStatus(project.id, index);
          } else {
            this.$message.error('评估启动失败，服务器返回错误代码');
          }
        })
        .catch(error => {
          this.$message.error('评估启动失败');
          console.error('Error:', error);
        });
      },
  
      pollProjectStatus(projectId, index) {
        const poll = setInterval(() => {
          axios.get(`http://localhost:8080/project/status?id=${projectId}`, {
            headers: {
              'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes'
            }
          })
          .then(response => {
            if (response.data.code === 1) {
              clearInterval(poll);
              this.projectDatas[index].status = '下一步';
            }
          })
          .catch(error => {
            console.error('Error polling project status:', error);
          });
        }, 3000);
      },
      goToNextStep() {
        this.$router.push({ name: 'ProjectConfirm' });
      }
    }
  }
  </script>
  
  <style scoped>
  .project-management-container {
    padding: 20px;
  }
  
  .header {
    display: flex;
    align-items: center;
    .form-item {
      display: flex;
      align-items: center;
      font-size: 14px;
      margin-right: 10px;
      span {
        flex-shrink: 0;
        color: #333;
        font-weight: bold;
      }
    }
  }
  
  .project-cards {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-top: 20px;
  }
  
  .project-card {
    width: 300px;
    border: 1px solid #ebebeb;
    padding: 15px;
  }
  
  .project-info {
    margin-bottom: 10px;
  }
  
  .block-pagination {
    width: 100%;
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
  }
  </style>
  